package com.inno.lock.config.redis;


import cn.hutool.core.util.IdUtil;
import com.inno.lock.processor.utils.LockApplicationContext;
import jakarta.annotation.Resource;

import java.util.concurrent.TimeUnit;

/**
 * @author shenzeyang
 * @Description: redis分布式锁工具类
 */

public class RedisLockUtil implements AutoCloseable{
    private final  String lockKey;
    private final String value;
    private final long expireTime;
    private final TimeUnit timeUnit;


    private final RedisUtil redisUtil;

    public RedisLockUtil(String lockKey, long expireTime, TimeUnit timeUnit) {
        this.lockKey = lockKey;
        this.value = IdUtil.fastUUID();
        this.expireTime = expireTime;
        this.timeUnit = timeUnit;
        this.redisUtil = LockApplicationContext.getBean("defaultRedisUtil",RedisUtil.class);
    }


    /**
     * 尝试获取锁
     */
    public boolean tryLock() {
        return this.redisUtil.setNx(lockKey, value, expireTime, timeUnit);
    }

    /**
     * 释放锁
     */
    public boolean unLock() {
        String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1] then\n" +
                "    return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                "    return 0\n" +
                "end";
        return  this.redisUtil.execute(script,lockKey,value);
    }


    /**
     * 方便起见 实现AutoCloseable接口，自动释放锁
     */
    @Override
    public void close() throws Exception {
        this.unLock();
    }

}
